package com.myres.orders.db;

import java.util.List;
import java.util.ArrayList;

import com.myres.model.Order;
import com.myres.model.OrderItem;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.myres.db.ConnectionPool;
public class OrderService {
	public Order getLatestOrderOfUser(int uid){
		Connection con=null;
		try{
		con=ConnectionPool.getPool().getConnection();
		PreparedStatement pstmt=con.prepareStatement("select * from res_orders where _user_id=?  and  year(_order_time)>=year(now()) and month(_order_time)>=month(now()) and DAY(_order_time)>=day(now()) order by _order_time desc limit 1 ");
		pstmt.setInt(1, uid);
		ResultSet rs=pstmt.executeQuery();
		List<Order> list=Order.populate(rs);
		con.close();
		if(list==null||list.size()==0) return null;
		return list.get(0);
		}catch(SQLException e){
			return null;
		}finally{
			try{
				con.close();
				}catch(Exception e){}
		}
	}
	public List<Order> getOrders(int uid){
		Connection con=null;
		try{
		con=ConnectionPool.getPool().getConnection();
		PreparedStatement pstmt=con.prepareStatement("select * from res_orders where _user_id=?  order by _order_time desc ");
		pstmt.setInt(1, uid);
		ResultSet rs=pstmt.executeQuery();
		List<Order> list=Order.populate(rs);
		con.close();
		return list;
		}catch(SQLException e){
			return null;
		}finally{
			try{
				con.close();
				}catch(Exception e){}
		}
	}
	public Order getOrderById(int id){
		Connection con=null;
		try{
		con=ConnectionPool.getPool().getConnection();
		PreparedStatement pstmt=con.prepareStatement("select * from res_orders where _id=?");
		pstmt.setInt(1, id);
		ResultSet rs=pstmt.executeQuery();
		List<Order> list=Order.populate(rs);
		con.close();
		if(list.size()==0)return null;
		return list.get(0);
		}catch(SQLException e){
			return null;
		}finally{
			try{
				con.close();
				}catch(Exception e){}
		}
		
	}
	public  List<Order> getNewOrders(){
		Connection con=null;
		try{
			con =ConnectionPool.getPool().getConnection();
			PreparedStatement pstmt=con.prepareStatement("select * from res_order where _state=0  order by _order_time desc");
			ResultSet rs=pstmt.executeQuery();
			return Order.populate(rs);
		}catch(SQLException e){
			e.printStackTrace();
			return null;
		}finally{
			try{
				con.close();
			}catch(Exception e){
				
			}
		}
	}
	public int setOrderState(int oid,int state){
		Connection con=null;
		try{
			con=ConnectionPool.getPool().getConnection();
			PreparedStatement pstmt=con.prepareStatement("update res_orders  set _state=? where _id=? ");
			pstmt.setInt(1, oid);
			pstmt.setInt(2, state);
			return pstmt.executeUpdate();
		}catch(SQLException e){
			e.printStackTrace();
			return -1;
		}finally{
			 try{
				 con.close();
			 }catch(Exception e){
				 
			 }
		}
	}
	
	
}
